package com.easyidea.its.web.action.user;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.easyidea.its.domain.model.system.Department;
import com.easyidea.its.domain.model.system.OperationRecord;
import com.easyidea.its.domain.model.system.PassPort;
import com.easyidea.its.domain.model.system.Role;
import com.easyidea.its.domain.model.system.User;
import com.easyidea.its.domain.service.operationrecord.OperationRecordService;
import com.easyidea.its.facade.user.UserMgr;
import com.easyidea.its.util.Config;
import com.easyidea.its.util.ItsConstants;
import com.easyidea.its.util.PageUtil;
import com.easyidea.its.util.Result;
import com.easyidea.its.util.SessionUtil;
import com.easyidea.its.web.action.base.ItsBaseAction;
import com.easyidea.its.web.dto.SeesionUserDto;
import com.easyidea.its.web.dto.UserDto;
import com.infowarelab.common.log.Log;
import com.infowarelab.common.log.LogFactory;
import com.opensymphony.webwork.ServletActionContext;

public class UserAction extends ItsBaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String FOOTER_DESCRIPTION = "footerDescription";
	private UserMgr userMgr;
	private String userName;
	private String password;

	private User user;

	private Result<User> userResult;

	private List<Role> roles;

	private Integer userId;

	private UserDto userDto = new UserDto();	
	private Collection<PassPort> allPassPorts; //所有卡口
	private Collection<PassPort> ownerPassPorts; //已管理卡口	
	private Collection<Department> allDepartments;
	private OperationRecordService operationRecordService;  
	private Integer[] passPortId;
	private static Log logger = LogFactory.getLog(UserAction.class);
	/**
	 * 用户登入
	 * @return
	 */
	public String doLogin() {
		HttpSession session = SessionUtil.getSession();
		SeesionUserDto userDto = userMgr.loginCheck(userName, password);
		if (null != userDto) {
			session.setAttribute("menuType", 1);
			if(session.getAttribute(ItsConstants.SESSION_KEY_USER_INFO) == null) {
				user = this.userMgr.getUserById(userDto.getUserId());
				buildOperatorRecord(user,"用户登录");
			}
			if (ServletActionContext.getServletContext().getAttribute(FOOTER_DESCRIPTION) == null) {
				ServletActionContext.getServletContext().setAttribute(FOOTER_DESCRIPTION, Config.getString("footer.description"));	
			}
			
			session.setAttribute(ItsConstants.SESSION_KEY_USER_INFO, userDto);
			
		} else {
			errorMsg = "用户名或密码不正确";
			return INPUT;
		}
		return SUCCESS;
	}
	private void buildOperatorRecord(User user,String operationContent) {
		OperationRecord or = new OperationRecord();
		or.setCreateTime(new Date());
		or.setCreator(user.getUserName());
		or.setModifier(user.getUserName());
		or.setModifyTime(new Date());
		or.setOperationContent(operationContent);
		or.setOperationDate(new Date());
		or.setOperationResult(operationContent + "成功!");
		or.setUser(user);
		operationRecordService.save(or);
	}

	/**
	 *用户列表 
	 * @return
	 */
	public String userList() {
		getAllRoles();
		getUserList();
		getAllDepts();
		return SUCCESS;
	}
	/**
	 * 新增
	 * @return
	 */
	public String initAddUser() {
		user = new User();
		getAllRoles();
		getAllDepts();
		return SUCCESS;
	}
	/**
	 * 查看
	 * @return
	 */
	public String viewUser() {
		getUserById();
		return SUCCESS;
	}
	/**
	 * 修改
	 * @return
	 */
	public String editUser() {
		getUserById();
		if (user == null) {
			return INPUT;
		}
		getAllRoles();
		getAllDepts();
		return SUCCESS;
	}


	private void getAllDepts() {
		allDepartments = userMgr.getAllDepartments();
	}
	/**
	 * 删除
	 * @return
	 */
	public String deleteUser() {
		try {
			 userMgr.deleteUserById(userId);
			 getSession().setAttribute(ItsConstants.SUCCESS_MSG, "delete.success");
		} catch (Exception e) {
			getSession().setAttribute("successMsg", "delete.user.failure");
		}
		return SUCCESS;
	}
  /**
   *保存 
   * @return
   */
	public String saveUser() {
		if (!userMgr.hasUser(user.getId(), user.getName())) {
			userMgr.saveOrUpdateUser(user);
			getSession().setAttribute(ItsConstants.SUCCESS_MSG, "save.success");
			return SUCCESS;
		} else {
			this.errorMsg ="用户名存在重复";
			return INPUT;
		}
	}

	/**
	 * 
	 */
	private boolean checkExistSameName() {
		// boolean bRet = userMgr.isExistSameName(user.getUserName(),
		// user.getId());
		// if (bRet) {
		// // setErrorMsg(ActionOperation.USER_NAME_EXIST_SAME_NAME.getI18n());
		// return false;
		// }
		return true;
	}

	public String saveUserForRegister() {
		if (checkExistSameName()) {
			// user.setUserType(USER_TYPE_REGISTER);
			// userMgr.saveOrUpdateUser(user, upload, uploadFileName);
			// successMsgKey =
			// StringUtil.toUtf8String(ActionOperation.ADDNEW_SUCCESS.getI18n());
			return SUCCESS;
		} else {
			return INPUT;
		}
	}

	public String updateUserForServiceManager() {
		// User tmpUser = userMgr.getUserByUserId(user.getId());
		User tmpUser = new User();
		if (tmpUser == null) {
			// this.setErrorMsgKey("el.admin.error.user.noexists");
			return ERROR;
		}
		if (checkExistSameName()) {
			saveOrUpdateUser();
			// successMsgKey =
			// StringUtil.toUtf8String(ActionOperation.UPDATE_SUCCESS.getI18n());
			return SUCCESS;
		} else {
			return INPUT;
		}
	}

	public String updateUserForRegister() {
		// User tmpUser = userMgr.getUserByUserId(user.getId());
		User tmpUser = new User();
		if (tmpUser == null) {
			// this.setErrorMsgKey("el.admin.error.user.noexists");
			return ERROR;
		}
		if (checkExistSameName()) {
			// userMgr.saveOrUpdateUser(user, upload, uploadFileName);
			// successMsgKey =
			// StringUtil.toUtf8String(ActionOperation.UPDATE_SUCCESS.getI18n());
			return SUCCESS;
		} else {
			return INPUT;
		}
	}

	/**
	 * 
	 */
	private void getUserById() {
		 user = this.userMgr.getUserByUserId(userId);
	}

	/**
	 * 
	 */
	private void saveOrUpdateUser() {
		userMgr.saveOrUpdateUser(user);
	}

	/**
	 * 
	 */
	private void getAllRoles() {
		roles = userMgr.getAllRoles();
	}

	/**
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void getUserList() {
		int totalRecords = this.userMgr.getUserCountByUserDto(userDto);
		if (totalRecords > 0) {
			int start = (this.currentPage - 1) * this.getPageSize();
			Collection<User> records = userMgr.getUsersByUserDto(userDto,
					start, this.getPageSize());
			userResult = PageUtil.createResult(this.getPageSize(), currentPage,
					totalRecords, records);
		} else {
			userResult = PageUtil.createResult(this.getPageSize(), currentPage,
					0, new ArrayList());
		}
	}
	public String assignUserPassPort() {
		User user = this.userMgr.getUserById(userId);
		if (user.getDepartment()!= null && user.getDepartment().getId() != null) {
			 userName = user.getUserName();
			 allPassPorts = userMgr.getAllPassPortByDeptId(user.getDepartment().getId());
			 logger.debug("owner"+user.getPassPortList());
			 ownerPassPorts = user.getPassPortList();
		}
		
		return SUCCESS;
	}
	public String saveUserPassPort() {
	   this.userMgr.saveUserPassPort(userId, passPortId);
		return SUCCESS;
	}
   public String doLogout() {
		if(this.getSession().getAttribute(ItsConstants.SESSION_KEY_USER_INFO) != null) {
			SeesionUserDto userDto = (SeesionUserDto)getSession().getAttribute(ItsConstants.SESSION_KEY_USER_INFO);
			user = this.userMgr.getUserById(userDto.getUserId());
			buildOperatorRecord(user,"用户注销");
		}	   
	   SessionUtil.getSession().invalidate();
	   return SUCCESS;
   }
	/**
	 * @return the userResult
	 */
	public Result<User> getUserResult() {
		return userResult;
	}

	/**
	 * @param userResult
	 *            the userResult to set
	 */
	public void setUserResult(Result<User> userResult) {
		this.userResult = userResult;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @param user
	 *            the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the roles
	 */
	public List<Role> getRoles() {
		return roles;
	}

	/**
	 * @param roles
	 *            the roles to set
	 */
	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public Collection<PassPort> getAllPassPorts() {
		return allPassPorts;
	}

	public void setAllPassPorts(Collection<PassPort> allPassPorts) {
		this.allPassPorts = allPassPorts;
	}

	public Collection<PassPort> getOwnerPassPorts() {
		return ownerPassPorts;
	}

	public void setOwnerPassPorts(Collection<PassPort> ownerPassPorts) {
		this.ownerPassPorts = ownerPassPorts;
	}

	public Integer[] getPassPortId() {
		return passPortId;
	}

	public void setPassPortId(Integer[] passPortId) {
		this.passPortId = passPortId;
	}
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public UserMgr getUserMgr() {
		return userMgr;
	}

	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}
	public Collection<Department> getAllDepartments() {
		return allDepartments;
	}

	public void setAllDepartments(Collection<Department> allDepartments) {
		this.allDepartments = allDepartments;
	}
	/**
	 * @return the userId
	 */
	public Integer getUserId() {
		return userId;
	}

	/**
	 * @param userId
	 *            the userId to set
	 */
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	public UserDto getUserDto() {
		return userDto;
	}


	public void setUserDto(UserDto userDto) {
		this.userDto = userDto;
	}
	public OperationRecordService getOperationRecordService() {
		return operationRecordService;
	}
	public void setOperationRecordService(
			OperationRecordService operationRecordService) {
		this.operationRecordService = operationRecordService;
	}



}
